package dao.impl;

import dao.UserDao;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner(DataSourceUtils.getDs());

    @Override
    public User findById(int id) {
        try {
            return qr.query("select * from user where id=?",new BeanHandler<>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<User> findAll() {
        try {
            return qr.query("select * from user",new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getCount() {
        try {
//            List<Map<String, Object>> maps = qr.query("SELECT gender,COUNT(1) total FROM USER GROUP BY gender", new MapListHandler());
            List<Map<String, Object>> maps = qr.query("SELECT gender,COUNT(1) 'total.a' FROM USER GROUP BY gender", new MapListHandler());
            return maps;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
